<template>
  <div class="app-container">
    <el-card header="AI 接口连通性测试">
      <el-alert
        title="测试前端与 Python FastAPI 后端的连接"
        type="info"
        description="这个页面用于验证代理配置是否正确"
        show-icon
        :closable="false"
        style="margin-bottom: 20px;"
      />

      <el-row :gutter="20">
        <!-- 连接测试 -->
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <span>🔗 健康检查</span>
            </template>
            <div style="text-align: center;">
              <el-button
                type="primary"
                :loading="testingConnection"
                @click="testConnection"
              >
                健康检查
              </el-button>
              <div style="margin-top: 10px;">
                <el-tag :type="connectionStatus.type">
                  {{ connectionStatus.text }}
                </el-tag>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 系统状态 -->
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <span>📊 系统状态</span>
            </template>
            <div style="text-align: center;">
              <el-button
                type="info"
                :loading="loadingStatus"
                @click="getSystemStatus"
              >
                获取状态
              </el-button>
              <div style="margin-top: 10px;">
                <el-tag v-if="systemStatus" type="success">
                  {{ systemStatus.status }}
                </el-tag>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 聊天测试 -->
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <span>💬 聊天测试</span>
            </template>
            <el-input
              v-model="testMessage"
              placeholder="输入测试消息..."
              style="margin-bottom: 10px;"
            />
            <el-select v-model="selectedModel" placeholder="选择模型" style="margin-bottom: 10px; width: 100%;">
              <el-option
                v-for="model in availableModels"
                :key="model.name"
                :label="model.name"
                :value="model.name"
              />
            </el-select>
            <el-button
              type="success"
              :loading="testingChat"
              @click="testChat"
              style="width: 100%;"
            >
              发送测试
            </el-button>
          </el-card>
        </el-col>

        <!-- 模型测试 -->
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <span>🤖 模型列表</span>
            </template>
            <div style="text-align: center;">
              <el-button
                type="warning"
                :loading="loadingModels"
                @click="getModels"
              >
                获取模型
              </el-button>
              <div style="margin-top: 10px;">
                <el-tag v-if="availableModels.length > 0" type="success">
                  {{ availableModels.length }} 个模型
                </el-tag>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 测试结果展示 -->
      <el-card header="测试结果" style="margin-top: 20px;">
        <el-collapse v-model="activeCollapse">
          <!-- 健康检查结果 -->
          <el-collapse-item title="健康检查结果" name="connection">
            <pre>{{ connectionResult }}</pre>
          </el-collapse-item>

          <!-- 系统状态结果 -->
          <el-collapse-item title="系统状态结果" name="status">
            <div v-if="systemStatus">
              <p><strong>状态:</strong>
                <el-tag :type="systemStatus.status === 'running' ? 'success' : 'danger'">
                  {{ systemStatus.status }}
                </el-tag>
              </p>
              <p><strong>活跃模型:</strong> {{ systemStatus.active_models.join(', ') }}</p>
              <p><strong>总请求数:</strong> {{ systemStatus.total_requests }}</p>
              <p><strong>运行时间:</strong> {{ (systemStatus.uptime / 60).toFixed(2) }} 分钟</p>
            </div>
            <div v-else>暂无数据</div>
          </el-collapse-item>

          <!-- 聊天结果 -->
          <el-collapse-item title="聊天测试结果" name="chat">
            <div v-if="chatResult">
              <p><strong>问题:</strong> {{ testMessage }}</p>
              <p><strong>回答:</strong> {{ chatResult.message.content }}</p>
              <p><strong>模型:</strong> {{ chatResult.model }}</p>
              <p><strong>处理时间:</strong> {{ (chatResult.processing_time * 1000).toFixed(2) }} ms</p>
              <p><strong>Token 使用:</strong>
                <span v-if="chatResult.usage">
                  输入: {{ chatResult.usage.prompt_tokens }},
                  输出: {{ chatResult.usage.completion_tokens }},
                  总计: {{ chatResult.usage.total_tokens }}
                </span>
                <span v-else>无数据</span>
              </p>
            </div>
            <div v-else>暂无数据</div>
          </el-collapse-item>

          <!-- 模型结果 -->
          <el-collapse-item title="模型列表结果" name="models">
            <el-table :data="availableModels" style="width: 100%">
              <el-table-column prop="name" label="模型名称" width="200"></el-table-column>
              <el-table-column prop="description" label="描述"></el-table-column>
              <el-table-column prop="max_tokens" label="最大Token">
                <template #default="scope">
                  {{ scope.row.max_tokens.toLocaleString() }}
                </template>
              </el-table-column>
              <el-table-column prop="is_available" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.is_available ? 'success' : 'danger'">
                    {{ scope.row.is_available ? '可用' : '不可用' }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
        </el-collapse>
      </el-card>

      <!-- 请求日志 -->
      <el-card header="请求日志" style="margin-top: 20px;">
        <el-timeline>
          <el-timeline-item
            v-for="(log, index) in requestLogs"
            :key="index"
            :timestamp="log.time"
            :type="log.type"
          >
            {{ log.message }}
          </el-timeline-item>
        </el-timeline>
      </el-card>
    </el-card>
  </div>
</template>

<script>
import { testAIConnection, testAIChat, getAIModels, getSystemStatus } from '@/api/ai/module1/module1'

export default {
  name: 'AIModule1',
  data() {
    return {
      // 测试状态
      testingConnection: false,
      testingChat: false,
      loadingModels: false,
      loadingStatus: false,

      // 测试数据
      testMessage: '你好，请介绍一下你自己',
      selectedModel: 'gpt-3.5-turbo',
      connectionStatus: { type: 'info', text: '未测试' },
      connectionResult: null,
      chatResult: null,
      systemStatus: null,
      availableModels: [],

      // UI 状态
      activeCollapse: ['connection', 'status', 'chat', 'models'],
      requestLogs: []
    }
  },
  methods: {
    // 添加日志
    addLog(type, message) {
      this.requestLogs.unshift({
        time: new Date().toLocaleTimeString(),
        type: type,
        message: message
      })
    },

    // 测试连接
    async testConnection() {
      this.testingConnection = true
      this.addLog('primary', '开始健康检查...')

      try {
        const response = await testAIConnection()
        this.connectionResult = response
        this.connectionStatus = { type: 'success', text: '健康' }
        this.addLog('success', `健康检查成功: ${response.status}`)
      } catch (error) {
        this.connectionStatus = { type: 'danger', text: '不健康' }
        this.connectionResult = error
        this.addLog('danger', `健康检查失败: ${error.message}`)
      } finally {
        this.testingConnection = false
      }
    },

    // 获取系统状态
    async getSystemStatus() {
      this.loadingStatus = true
      this.addLog('primary', '获取系统状态...')

      try {
        const response = await getSystemStatus()
        this.systemStatus = response
        this.addLog('success', `系统状态: ${response.status}`)
        this.$message.success('系统状态获取成功')
      } catch (error) {
        this.systemStatus = null
        this.addLog('danger', `获取系统状态失败: ${error.message}`)
        this.$message.error('获取系统状态失败')
      } finally {
        this.loadingStatus = false
      }
    },

    // 测试聊天
    async testChat() {
      if (!this.testMessage.trim()) {
        this.$message.warning('请输入测试消息')
        return
      }

      this.testingChat = true
      this.addLog('primary', `发送消息到 ${this.selectedModel}: ${this.testMessage}`)

      try {
        const response = await testAIChat(this.testMessage)
        this.chatResult = response
        this.addLog('success', `收到回复: ${response.message.content}`)
        this.$message.success('聊天测试成功')
      } catch (error) {
        this.chatResult = null
        this.addLog('danger', `聊天失败: ${error.message}`)
        this.$message.error('聊天测试失败')
      } finally {
        this.testingChat = false
      }
    },

    // 获取模型列表
    async getModels() {
      this.loadingModels = true
      this.addLog('primary', '获取模型列表...')

      try {
        const response = await getAIModels()
        this.availableModels = response
        this.addLog('success', `获取到 ${this.availableModels.length} 个模型`)
        this.$message.success(`获取到 ${this.availableModels.length} 个模型`)

        // 自动选择第一个可用模型
        const availableModel = this.availableModels.find(model => model.is_available)
        if (availableModel) {
          this.selectedModel = availableModel.name
        }
      } catch (error) {
        this.availableModels = []
        this.addLog('danger', `获取模型失败: ${error.message}`)
        this.$message.error('获取模型列表失败')
      } finally {
        this.loadingModels = false
      }
    }
  },

  mounted() {
    this.addLog('info', 'AI 测试页面加载完成')
    // 页面加载时自动获取模型列表
    this.getModels()
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
pre {
  background: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
  overflow: auto;
}
</style>
